﻿using System;
using CiStatus.CiStatusAddIn.Logic.Exceptions;
using CiStatus.CiStatusAddIn.Logic.PluginInterfaces;
using CiStatus.CiStatusAddIn.Logic.Status;

namespace CiStatus.CiStatusAddIn.Logic
{
    public class RefreshCiStatus : IRefreshCiStatus
    {
        private readonly ICiPoller _poller;
        private IStatus _previousStatus;
        private IStatus _currentStatus;

        public RefreshCiStatus(ICiPoller poller, IStatus statusAtStart)
        {
            _poller = poller;
            _previousStatus = statusAtStart;
            _currentStatus = statusAtStart;
        }

        public IStatus Refresh(ICallBack callBack)
        {
            try
            {
                var currentStatus = _poller.CurrentStatus();

                if (!CurrentStatus.Equals(currentStatus))
                {
                    _previousStatus = CurrentStatus;
                }
                _currentStatus = currentStatus;
                callBack.Notify();
            }
            catch(CommunicationPollerException epe)
            {
                var details = new StatusDetails
                                  {
                                      Message = epe.Message
                                  };
                _currentStatus = new StatusOffline(details);
            }
            return CurrentStatus;
        }

        public IStatus PreviousStatus
        {
            get { return _previousStatus; }
        }

        public IStatus CurrentStatus
        {
            get { return _currentStatus; }
        }
    }
}
